<?php

/**
 * This is the model class for table "{{transactionmaster}}".
 *
 * The followings are the available columns in table '{{transactionmaster}}':
 * @property integer $idtransactionmaster
 * @property string $transactionmastervoucherdate
 * @property string $transactionmasternarration
 * @property integer $idvouchertype
 *
 * The followings are the available model relations:
 * @property Transactiondetails[] $transactiondetails
 * @property Vouchertype $idvouchertype0
 * @property Transactionsalespurchase[] $transactionsalespurchases
 */
class Transactionmaster extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @return Transactionmaster the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{transactionmaster}}';
    }

    public $transactioncrdr;
    public $acledger;
    public $transactionamount;

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
//            array('transactionmastervoucherdate, transactionmasternarration, idvouchertype', 'required'),
            array('idvouchertype', 'numerical', 'integerOnly' => true),
            array('transactionmasternarration', 'length', 'max' => 255),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
//            array('idtransactionmaster, transactionmastervoucherdate, transactionmasternarration, idvouchertype', 'safe', 'on' => 'search'),
//            array('yii_vouchertype', 'autocompleteValidator', 'model' => 'Vouchertype'),
            array('transactioncrdr, acledger, transactionamount', 'unsafe'),
            array('transactioncrdr', 'transactionmasterValidator'),
            array('acledger', 'transactionmasterValidator'),
            array('transactionamount', 'transactionmasterValidator'),
        );
    }

    public function transactionmasterValidator($attribute, $params) {
//        $this->addError($attribute, "Error1");
//        $this->addError("transactionmasternarration", "Error");
//        if ($_REQUEST['Transactionmaster']['acledger'] != '' && $_REQUEST['Transactionmaster']['transactionamount'] != '') {
        syslog(LOG_WARNING, '--->>>>transactionValidator -- ' . $attribute);
        if ($attribute == 'transactioncrdr') {
//            syslog(LOG_WARNING, 'transactioncrdrValidator - ' . $attribute . ' - ' . $_REQUEST['Transactionmaster'][$attribute]);
            if ($_REQUEST['Transactionmaster'][$attribute] != "CR" && $_REQUEST['Transactionmaster'][$attribute] != "DR") {
                $this->addError($attribute, "Error");
            }
        }
        if ($attribute == 'acledger') {
            syslog(LOG_WARNING, 'first line acledger-- ' . $_REQUEST['Transactionmaster']['transactioncrdr']);
//            if ($_REQUEST['Transactionmaster']['transactioncrdr'] == "CR" || $_REQUEST['Transactionmaster']['transactioncrdr'] == "DR") {


                if (isset($_REQUEST['Transactionmaster'][$attribute]) && $_REQUEST['Transactionmaster'][$attribute] != '') {
                    $type = isset($_REQUEST['idvouchertype']) ? $_REQUEST['idvouchertype'] : '';
                    foreach($_REQUEST as $key => $value){
                        syslog(LOG_WARNING, "$key -> $value");
                    }
                    $transactioncrdr = isset($_REQUEST['Transactionmaster']['transactioncrdr']) ? $_REQUEST['Transactionmaster']['transactioncrdr'] : '';
                    $rulescolumn = strtolower(Vouchertype::model()->findByPk($type)->vouchertype . $transactioncrdr);
                    $match = addcslashes($_REQUEST['Transactionmaster'][$attribute], '%_');
                    syslog(LOG_WARNING, 'validateacledger-- ' . $rulescolumn . ' - ' . $match . ' - ');
                    $criteria = new CDbCriteria(array(
                                'with' => array('idacgroup0', 'idacgroup0.idrules0'),
                                'condition' => 'acledgername LIKE :acledgername And idrules0.' . $rulescolumn . '=1',
                                'params' => array(':acledgername' => "%$match%")
                            ));
                    syslog(LOG_WARNING, 'criteria- ');
                    $exists = Acledger::model()->exists($criteria);
                    syslog(LOG_WARNING, 'acledgerafterexists- ' . $rulescolumn . ' - ' . $match . ' - ' . $exists);

                    if (!$exists) {
                        $this->addError($attribute, "Error2");
                    }
                } else {
                        $this->addError($attribute, "Error3");
                    
                }                
//            }
        }
        
        if ($attribute == 'transactionamount') {
                    syslog(LOG_WARNING, 'validaitetransationamount- ');
                    if(!is_numeric($_REQUEST['Transactionmaster'][$attribute]) || $_REQUEST['Transactionmaster'][$attribute] <=0){
                        $this->addError($attribute, "Error");                        
                    }
            
//            if ($_REQUEST['Transactionmaster']['transactioncrdr'] == "CR" || $_REQUEST['Transactionmaster']['transactioncrdr'] == "DR") {
//                if (isset($_REQUEST['Transactionmaster']['acledger']) && $_REQUEST['Transactionmaster']['acledger'] != '') {
//                    if(!is_numeric($_REQUEST['Transactionmaster'][$attribute]) || $_REQUEST['Transactionmaster'][$attribute] <=0){
//                        $this->addError($attribute, "Error");                        
//                    }
//                }                
//            }
        }        
        
//        }
//        syslog(LOG_WARNING, 'transactioncrdrValidator - ' . $attribute . ' - ' . ((isset($_REQUEST['Transactionmaster'][$attribute])) ? 'y' : 'n') . ' --- ' . $_REQUEST['Transactionmaster'][$attribute]);
    }

    public function autocompleteValidator($attribute, $params) {
        $match = addcslashes($_REQUEST[$attribute], '%_');
        if (!$params['model']::model()->exists(new CDbCriteria(array(
                            'condition' => "$attribute = :$attribute",
                            'params' => array(":$attribute" => "$match")
                        )))) {
            $this->addError($attribute, Yii::t('application', 'Incorrect {attribute}.', array('{attribute}' => Yii::t('application', $attribute))));
        }
    }

    public function beforeSave() {
        if (isset($_REQUEST['yii_vouchertype'])) {
            $match = addcslashes($_REQUEST['yii_vouchertype'], '%_'); // escape LIKE's special characters
            $criteria = new CDbCriteria(array(
                        'condition' => 'yii_vouchertype = :yii_vouchertype',
                        'params' => array(':yii_vouchertype' => "$match")
                    ));
            $model = Vouchertype::model()->find($criteria);
            $this->idvouchertype = $model->idvouchertype;
        }
        return parent::beforeSave();
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'transactiondetails' => array(self::HAS_MANY, 'Transactiondetails', 'idtransactionmaster'),
            'idvouchertype0' => array(self::BELONGS_TO, 'Vouchertype', 'idvouchertype'),
            'transactionsalespurchases' => array(self::HAS_MANY, 'Transactionsalespurchase', 'idtransactionmaster'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'idtransactionmaster' => Yii::t('application', 'Idtransactionmaster'),
            'transactionmastervoucherdate' => Yii::t('application', 'Transactionmastervoucherdate'),
            'transactionmasternarration' => Yii::t('application', 'Transactionmasternarration'),
            'idvouchertype' => Yii::t('application', 'Idvouchertype'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('idtransactionmaster', $this->idtransactionmaster);
        $criteria->compare('transactionmastervoucherdate', $this->transactionmastervoucherdate, true);
        $criteria->compare('transactionmasternarration', $this->transactionmasternarration, true);
        $criteria->compare('idvouchertype', $this->idvouchertype);
        $criteria->order = 'idtransactionmaster desc';

        return new CActiveDataProvider(get_class($this), array(
                    'criteria' => $criteria,
                ));
    }

    public function getVouchertypeArray() {
        $codes = Vouchertype::model()->findAll();
        $data = array(); // data to be returned
        foreach ($codes as $c) {
            $data[$c->idvouchertype] = $c->vouchertype;
        }
        return $data;
    }

    public function transactiondetailsDataProvider($idtransactionmaster) {
        Yii::app()->clientscript->scriptMap['jquery.js'] = false;
        Yii::app()->clientscript->scriptMap['jquery-ui.min.js'] = false;

        //syslog(LOG_WARNING, $idtransactionmaster);
        $vouchers = Yii::app()->session['vouchers'];
        if (!isset($vouchers)) {
            $vouchers = array();
//            $vouchers[] = array('id' => 0, 'transactioncrdr' => 'CR', 'acledger'=>'');

            if ($idtransactionmaster > 0) {
                $transactiondetailss = Transactiondetails::model()->findAll('idtransactionmaster=:idtransactionmaster', array(':idtransactionmaster' => $idtransactionmaster));
                foreach ($transactiondetailss as $transactiondetails) {
                    $vouchers[count($vouchers)] = array('id' => count($vouchers), 'transactioncrdr' => $transactiondetails->transactioncrdr, 'acledger' => $transactiondetails->idacledger0->acledgername, 'transactionamount' => $transactiondetails->transactionamount, 'credit' => $transactiondetails->transactioncrdr == 'CR' ? $transactiondetails->transactionamount : '', 'debit' => $transactiondetails->transactioncrdr == 'DR' ? $transactiondetails->transactionamount : '');
                    //syslog(LOG_WARNING, print_r($vouchers, true));
                }
            }
            Yii::app()->session['vouchers'] = $vouchers;
        }
        $dataProvider = new CArrayDataProvider($vouchers, array(
                    'id' => 'transactiondetailsDataProvider',
                ));
        return $dataProvider;
    }

}